package cn.boot.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;

import cn.boot.common.BaseAction;
import cn.boot.entity.SessionBean;
import cn.boot.entity.UserMailConfig;
import cn.boot.entity.main.SimpleUser;
import cn.boot.entity.main.SysUser;
import cn.boot.entity.main.User;
import cn.boot.service.BizService;
import mailclient.system.MailContext;
import mailclient.system.MainFrame;
import mailclient.util.FileUtil;
import util.Constant;
import util.MD5;
import util.MessageUtil;
import util.StringUtil;
import util.menu.MenuBean;
import util.menu.SubMenu;

@Controller
@RequestMapping("/com")
public class LoginAction extends BaseAction {
	@Autowired
	private BizService service;

	@RequestMapping(value = "/menu.do")
	@ResponseBody
	public Object menu() {

		int index = 0;

		List<MenuBean> list = new ArrayList<MenuBean>();
		if (getSessionUser() instanceof SysUser) {
			MenuBean m1 = new MenuBean("系统管理", "windows");
			m1.addChild(new SubMenu("navtab" + (index++), "用户管理", "navtab", request.getContextPath() + "/sys/querySimpleUser.do", "user"));
			m1.addChild(new SubMenu("navtab" + (index++), "管理员管理", "navtab", request.getContextPath() + "/sys/querySysUser.do", "user"));
//			m1.addChild(new SubMenu("navtab" + (index++), "过滤词管理", "navtab", request.getContextPath() + "/sys/queryWords.do", "bug"));
			list.add(m1);

		}
		if (getSessionUser() instanceof SimpleUser) {
			MenuBean m1 = new MenuBean("系统管理", "windows");
			m1.addChild(new SubMenu("navtab" + (index++), "写信", "navtab", request.getContextPath() + "/sys/xie.do", "send-o"));
			m1.addChild(new SubMenu("navtab" + (index++), "收件箱", "navtab", request.getContextPath() + "/sys/shou.do", "envelope-o"));
			m1.addChild(new SubMenu("navtab" + (index++), "已发送", "navtab", request.getContextPath() + "/sys/yiFa.do", "paw"));
			m1.addChild(new SubMenu("navtab" + (index++), "已删除", "navtab", request.getContextPath() + "/sys/yiShan.do", "trash-o"));
//			m1.addChild(new SubMenu("navtab" + (index++), "垃圾箱", "navtab", request.getContextPath() + "/sys/laji.do", "bug"));
			m1.addChild(new SubMenu("navtab" + (index++), "草稿箱", "navtab", request.getContextPath() + "/sys/queryDraft.do", "file-code-o"));
			m1.addChild(new SubMenu("navtab" + (index++), "联系人", "navtab", request.getContextPath() + "/sys/queryContact.do", "bookmark-o"));
			m1.addChild(new SubMenu("navtab" + (index++), "邮箱配置", "navtab", request.getContextPath() + "/sys/getUserMailConfig.do", "certificate"));
			list.add(m1);
		}
		return list;
	}

	public MailContext createContext(SimpleUser user) {
		try {
			List<UserMailConfig> clist = (List<UserMailConfig>) service.queryByHQL("from UserMailConfig where user.id=?", user.getId());
			UserMailConfig cfg = null;
			if (!clist.isEmpty()) {
				cfg = clist.get(0);
			} else {
				cfg = new UserMailConfig();
			}
			getHttpSession().setAttribute(Constant.SESSION_MAIL_CONFIG, cfg);

			return new MailContext(null, cfg.getAccount(), cfg.getPassword(), cfg.getSmtpHost(), cfg.getSmtpPort(), cfg.getPop3Host(), cfg.getPop3Port());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private void initMail(SimpleUser user) {
		try {
			//得到用户名对应的目录
			File folder = new File(FileUtil.DATE_FOLDER + user.getUser().getUname());
			//该用户第一次进入系统， 创建目录
			if (!folder.exists()) {
				folder.mkdir();
			}
			MailContext ctx = createContext(user);
			ctx.setUser(user.getUser().getUname());
			log.info(ctx);
			MainFrame bean = new MainFrame(ctx);
			bean.words = service.queryByHQL("from Words");
			getHttpSession().setAttribute(Constant.SESSION_MAIL_BEAN, bean);
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String login(String loginid, String password, String logintype, String checkcode) throws Exception {
		log.info(loginid + " " + password + " " + logintype);
		String errorMessage = null;
		try {
			String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (code == null) {
				request.getSession(false).invalidate();
				return "redirect:/index.jsp";
			} else {
			}
			checkcode = StringUtil.stringVerification(checkcode);
			if (code.toLowerCase().equals(checkcode.toLowerCase())) {
				loginid = StringUtil.stringVerification(loginid).toLowerCase();
				MD5 md = new MD5();
				password = md.getMD5ofStr(password);
				Object user = service.findUser(logintype, loginid, password);
				if (user != null) {

					SessionBean sb = new SessionBean();
					sb.setUser(user);

					session.setAttribute(Constant.SESSION_BEAN, sb);

					log.info("登录成功:" + loginid);
					if (user instanceof SimpleUser) {
						SimpleUser tempuser = (SimpleUser) user;
						initMail(tempuser);
						UserMailConfig temp = service.unique("from UserMailConfig where user.id=?", getSimpleUser().getId());
						request.setAttribute("modifybean", temp);
					}

				} else {
					errorMessage = "登录帐号或者密码错误";
				}
			} else {
				errorMessage = "验证码错误";
			}
			if (errorMessage == null) {
				return "main";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (errorMessage == null) {
			errorMessage = "登录失败,请稍候重试";
		}
		session.setAttribute("signErrorMessage", errorMessage);
		return "redirect:/index.jsp";
	}

	@RequestMapping(value = "/reg.do")
	public String reg(SimpleUser bean) throws Exception {
		String msg = "";
		try {
			Object temp = service.unique("from User where uname=?", bean.getUser().getUname());
			if (temp != null) {
				msg = "账号已经被使用了";
			} else {
				bean.getUser().setUserGender(1);
				service.addSimpleUser(bean);
				msg = "注册成功";
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg = "注册失败";
		}
		session.setAttribute("signErrorMessage", msg);
		return "redirect:/reg.jsp";
	}

	@RequestMapping(value = "/toSelf.do")
	public String toSelf() {
		return "msg/changepassword";
	}

	@RequestMapping(value = "/updatePassword.do", method = RequestMethod.POST)
	public String updatePassword(String oldpassword, String password) {
		try {
			User user = null;
			SessionBean sb = (SessionBean) session.getAttribute(Constant.SESSION_BEAN);
			Object sbuser = sb.getUser();
			if (SysUser.class.getSimpleName().equals(sb.getRole())) {
				user = ((SysUser) sbuser).getUser();
			} else if (SimpleUser.class.getSimpleName().equals(sb.getRole())) {
				user = ((SimpleUser) sbuser).getUser();
			}
			MD5 md = new MD5();
			oldpassword = md.getMD5ofStr(oldpassword);

			if (!user.getUserPassword().equals(oldpassword)) {
				MessageUtil.addMessage(request, "旧密码错误.");
				return ERROR;
			}

			password = md.getMD5ofStr(password);
			user.setUserPassword(password);

			service.update(user);

			MessageUtil.addMessage(request, "修改成功.");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(request, "修改失败.");
			return ERROR;
		}
	}

	@RequestMapping(value = "/modifySelf.do", method = RequestMethod.POST)
	public String modifySelf(User bean) {
		try {
			User sessionUser = null;
			SessionBean sb = (SessionBean) session.getAttribute(Constant.SESSION_BEAN);
			Object sbuser = sb.getUser();
			if (SysUser.class.getSimpleName().equals(sb.getRole())) {
				sessionUser = ((SysUser) sbuser).getUser();
			} else if (SimpleUser.class.getSimpleName().equals(sb.getRole())) {
				sessionUser = ((SimpleUser) sbuser).getUser();
			}
			log.info(bean.getUserAddress());
			bean.setUserId(sessionUser.getUserId());
			bean.setUname(sessionUser.getUname());
			if (StringUtil.notEmpty(bean.getUserPassword())) {
				MD5 md = new MD5();
				String password = md.getMD5ofStr(bean.getUserPassword());
				bean.setUserPassword(password);
			} else {
				bean.setUserPassword(sessionUser.getUserPassword());
			}
			service.update(bean);

			sessionUser.setUserAddress(bean.getUserAddress());
			sessionUser.setUserBirth(bean.getUserBirth());
			sessionUser.setUserEmail(bean.getUserEmail());
			sessionUser.setUserGender(bean.getUserGender());
			sessionUser.setUserName(bean.getUserName());
			sessionUser.setUserPhone(bean.getUserPhone());

			MessageUtil.addMessage(request, "修改成功.");
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			MessageUtil.addMessage(request, "修改失败.");
			return ERROR;
		}
	}

	@RequestMapping(value = "/logout.do")
	public String logout() {
		try {
			MainFrame bean = (MainFrame) getHttpSession().getAttribute(Constant.SESSION_MAIL_BEAN);
			if (bean != null) {
				bean.stop();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		session.invalidate();
		return "redirect:/exit.jsp";
	}

	@RequestMapping(value = "/fileUpload.do", method = RequestMethod.POST)
	@ResponseBody
	public Object image(HttpServletRequest request, HttpSession session, @RequestParam("file") MultipartFile file) throws Exception {

		final String prefix = "resource";

		final String realPath = session.getServletContext().getRealPath(prefix);
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 取得原文件名
		String originName = file.getOriginalFilename();
		// 取得文件后缀
		String fileExt = originName.substring(originName.lastIndexOf(".") + 1);
		// 按时间戳生成图片文件名
		String picture = new Date().getTime() + "_" + originName;
		FileOutputStream fout = new FileOutputStream(new File(dir, picture));
		try {
			IOUtils.copy(file.getInputStream(), fout);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fout.close();
			} catch (Exception e) {
			}
		}
		// {'err':'',msg:{'url':'XXX/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}
		//String json = String.format("{'statusCode':200,'message':'上传成功!','filename':'%s'}", picture);
		JSONObject obj = new JSONObject();
		obj.put("statusCode", 200);
		obj.put("message", "");
		obj.put("filename", picture);
		return obj;
	}
	/**
	<label class="row-label">文件上传</label>
	<div class="row-input">
		<input type="file" data-name="upload" name="upload" data-toggle="webuploader"
			data-options="
	               {
	                   pick: {label: '点击选择文件'},
	                   server: '${ctx}/com/fileUpload.do',
	                   fileNumLimit: 1,
	                   fileSizeLimit: 10000000000,
		               fileSingleSizeLimit: 10000000000,
	                   formData: {dir:'upload'},
	                   required: true,
	                   uploaded: '',
	                   basePath: '',
	                   upunit: '个文件',
	                   accept: {
	                       title: '文件',
	                       extensions: 'jpg,png',
	                       mimeTypes: '.jpg,.png'
	                   }
	               }">
	</div>
	<br />
	*/

	/**
		<br />
		<label class="row-label">内容编辑</label>
		<div class="row-input">
			<textarea name="content" id="j_form_content" class="j-content" style="width: 700px;" data-toggle="kindeditor"
				data-items="fontname, fontsize, |, forecolor, hilitecolor, bold, italic, underline, removeformat, |, justifyleft, justifycenter, justifyright, insertorderedlist, insertunorderedlist, |, emoticons, image, link"
				data-minheight="200px">${modifybean.content}</textarea>
		</div>
	*/

}
